package com.atguigu.edu.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.app.func.DimSinkFunction;
import com.atguigu.edu.realtime.app.func.TableProcessFunction;
import com.atguigu.edu.realtime.bean.TableProcess;
import com.atguigu.edu.realtime.util.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

public class DimSinkApp {
    public static void main(String[] args) throws Exception {
        // TODO 1. 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);


        // TODO 3. 读取业务主流
        //3.1 声明消费主题以及消费者组
        String topic = "topic_db";
        String groupId = "dim_sink_app";
        //3.2 获取消费者对象
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);
        //3.3 消费数据 得到流
        DataStreamSource<String> dbStrDS = env.addSource(kafkaConsumer);


        // TODO 4. 对读取的流中数据结构转换
        SingleOutputStreamOperator<JSONObject> jsonDS = dbStrDS.map(JSON::parseObject);

        // TODO 5. 主流 ETL
        SingleOutputStreamOperator<JSONObject> filterDS = jsonDS.filter(
                new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        try {
                            jsonObj.getJSONObject("data");
                            if (jsonObj.getString("type").equals("bootstrap-start")
                                    || jsonObj.getString("type").equals("bootstrap-complete")) {
                                return false;
                            }
                            return true;
                        } catch (JSONException jsonException) {
                            return false;
                        }
                    }
                });
        // 打印测试

        // TODO 6. FlinkCDC 读取配置流并广播流
// 6.1 FlinkCDC 读取配置表信息
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
                .hostname("hadoop101")
                .port(3306)
                .databaseList("edu_config") // set captured database
                .tableList("edu_config.table_process") // set captured table
                .username("root")
                .password("wuzu-3realtime")
                .deserializer(new JsonDebeziumDeserializationSchema())
                .startupOptions(StartupOptions.initial())
                .build();

// 6.2 封装为流
        DataStreamSource<String> mysqlDS
                = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "MysqlSource");

        mysqlDS.print("m>>>>>>>");
// 6.3 广播配置流
        MapStateDescriptor<String, TableProcess> tableConfigDescriptor
                = new MapStateDescriptor<String, TableProcess>("table-process-state", String.class, TableProcess.class);
        BroadcastStream<String> broadcastDS = mysqlDS.broadcast(tableConfigDescriptor);



        // TODO 7. 将主流和配置流进行关联
        BroadcastConnectedStream<JSONObject, String> connectedStream = filterDS.connect(broadcastDS);


        // TODO 8. 处理关联后数据
        SingleOutputStreamOperator<JSONObject> dimDS = connectedStream.process(
                new TableProcessFunction(tableConfigDescriptor)
        );

        // TODO 9. 将数据写入 Phoenix 表
        dimDS.addSink(new DimSinkFunction());

        env.execute();

    }
}

